package com.nomito.minimito.service.impl;
//雪花算法
import com.baomidou.mybatisplus.core.toolkit.IdWorker;

import com.nomito.minimito.common.constant.MsgSignFlagEnum;
import com.nomito.minimito.entity.ImMsgEntity;
import com.nomito.minimito.common.constant.SearchFriendsStatusEnum;
import com.nomito.minimito.entity.ImFriendEntity;
import com.nomito.minimito.externalUtils.maqueUtils.MD5Utils;
import com.nomito.minimito.netty.ChatMsg;
import com.nomito.minimito.service.ImFriendService;
import com.nomito.minimito.vo.GrouperVo;
import com.nomito.minimito.vo.NoExistGroupMemberVo;
import com.nomito.minimito.vo.UserInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import com.nomito.minimito.service.ImMsgService;
import org.springframework.stereotype.Service;

import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nomito.minimito.common.utils.PageUtils;
import com.nomito.minimito.common.utils.Query;

import com.nomito.minimito.dao.ImUserDao;
import com.nomito.minimito.entity.ImUserEntity;
import com.nomito.minimito.service.ImUserService;

@Service("imUserService")
public class ImUserServiceImpl extends ServiceImpl<ImUserDao, ImUserEntity> implements ImUserService {

    @Autowired
    ImMsgService msgService;


    @Autowired
    ImFriendService imFriendService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<ImUserEntity> page = this.page(
                new Query<ImUserEntity>().getPage(params),
                new QueryWrapper<ImUserEntity>()
        );

        return new PageUtils(page);
    }


    @Override
    public Integer searchFriend(String myUsername, String friendUsername) {
        /**
         * 1.好友不存在
         * 2.搜索的是自己
         * 3.搜索的是自己的好友
         * 4.新朋友
         */
        ImUserEntity userEntityM = this.getOne(new QueryWrapper<ImUserEntity>().eq("myUsername", myUsername));
        ImUserEntity userEntityF = this.getOne(new QueryWrapper<ImUserEntity>().eq("username", friendUsername));

        if (userEntityF == null){
            return SearchFriendsStatusEnum.USER_NOT_EXIST.code;
        }
        if (userEntityF.getId().equals(userEntityM.getId())){
            return SearchFriendsStatusEnum.NOT_YOURSELF.code;
        }
        Long myId = userEntityM.getId();
        Long friendId = userEntityF.getId();
        /**
         * 根据我自己的Id带im_friend表中找到我的好友列表
         * 判断我的还有列表里有没有此好友的信息
         */

        /**
        List<ImFriendEntity> entities = imFriendService.list(new QueryWrapper<ImFriendEntity>().eq("user_id", myId));
        List<ImFriendEntity> entity = entities.stream().map(v -> {
            Long friendId1 = v.getFriendId();
            return imFriendService.getOne(new QueryWrapper<ImFriendEntity>()
                    .eq("friend_id", friendId1).eq("friend_id",friendId));
        }).collect(Collectors.toList());
         if(entity.size()!= 0){
         return SearchFriendsStatusEnum.ALREADY_FRIENDS.code;
         }
         else return SearchFriendsStatusEnum.SUCCESS.code;
         */
        ImFriendEntity friendEntity = imFriendService.getOne(new QueryWrapper<ImFriendEntity>().eq("friend_id", friendId));
        if (myId.equals(friendEntity.getId())){
            return SearchFriendsStatusEnum.ALREADY_FRIENDS.code;
        }
        else return SearchFriendsStatusEnum.SUCCESS.code;
    }



    @Override
    public Long saveMsg(ChatMsg chatMsg) {
        ImMsgEntity msgEntity = new ImMsgEntity();
        long msgId = IdWorker.getId(msgEntity);
        msgEntity.setId(msgId);
        msgEntity.setAcceptUserId(chatMsg.getReceiverId());
        msgEntity.setSendUserId(chatMsg.getSenderId());
        msgEntity.setIsSigned(MsgSignFlagEnum.unsign.type);
        msgEntity.setMessage(chatMsg.getMsg());

        msgService.save(msgEntity);

        return msgId;
    }

    @Override
    public ImUserEntity login(String username, String password) {
        //查询用户是否存在
      try {
          ImUserEntity imUserEntity = this.baseMapper.selectOne(new QueryWrapper<ImUserEntity>().eq("username", username));
          if (imUserEntity != null) {//用户存在
              //若存在 校验密码是否一致
              if (MD5Utils.getPwd(password).equals(imUserEntity.getPassword())) {
                  return imUserEntity;//密码正确
              } else
                  return null;//密码错误
          } else {//用户不存在
              return null;//该用户不存在
          }
      }catch (Exception e){
          return  null;//存在异常
      }
    }

    @Override
    public Integer register(String username, String password) {
        try {
            //校验用户名唯一性

            ImUserEntity imUserEntity = this.baseMapper.selectOne(new QueryWrapper<ImUserEntity>().eq("username", username));
            if (imUserEntity != null) {//用户存在
               return 0;//该用户已存在
            } else {//用户不存在
                ImUserEntity imUserEntity1 = new ImUserEntity();
                imUserEntity1.setUsername(username);
                imUserEntity1.setPassword(MD5Utils.getPwd(password));
                boolean save = this.save(imUserEntity1);
                if(save){
                    return 1;//注册成功
                }else {
                    return 2;//注册失败
                }
            }
        }catch (Exception e){
            return 3;//存在异常
        }

    }

    @Override
    public GrouperVo getUserInfo(Long userId) {
        return baseMapper.getUserInfo(userId);
    }

    @Override
    public NoExistGroupMemberVo noExistGroupMember(Long userId) {
        //TODO 没做逻辑删除校验

        return baseMapper.noExistGroupMember(userId);
    }


    @Override
    public UserInfoVo queryUserInfo(Long userId) {
        return baseMapper.queryUserInfo(userId);
    }

}